package com.fadadianqi.logistics.admin.controller;

import com.fadadianqi.logistics.admin.controller.form.AjaxResult;
import com.fadadianqi.commons.Constants;
import com.fadadianqi.commons.JSONProvider;
import com.fadadianqi.goods.model.Brand;
import com.fadadianqi.goods.model.BrandCategoryRelation;
import com.fadadianqi.goods.service.GoodsService;
import com.yeqiangwei.commons.util.Pagination;
import com.yeqiangwei.commons.util.PaginationHelper;
import com.yeqiangwei.commons.util.ParamUtils;
import com.yeqiangwei.commons.util.ValidatorHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

import static com.fadadianqi.logistics.admin.controller.URIMappingUtils.INVENTORY_PREFIX;

@Controller("admin_brandController")
public class BrandController {

    private static final Log log = LogFactory.getLog(BrandController.class);

    private static final String URI_SAVE = INVENTORY_PREFIX + "/ajax/brand/save";
    private static final String URI_AJAX_GET = INVENTORY_PREFIX + "/ajax/brand/{id}";

    private static final String COMMAND_NAME = "brandForm";


    private static final String URI_AJAX_LIST = INVENTORY_PREFIX + "/ajax/brand/list";
    private static final String VIEW_AJAX_LIST = "admin/brand/ajaxList";

    private List<Brand> autoFindBrand(String categoryId) {
        List<Brand> list = null;
        if (ValidatorHelper.isNotEmpty(categoryId)) {
            List<BrandCategoryRelation> bcrList = goodsService.findRelationBrand(categoryId);
            if (ValidatorHelper.isNotEmpty(bcrList)) {
                list = new ArrayList<Brand>();
                for (BrandCategoryRelation bcr : bcrList) {
                    Brand b = goodsService.getBrandById(bcr.getBrandId());
                    list.add(b);
                }
            }
        } else {
            list = goodsService.findAllBrand();
        }
        return list;
    }

    /**
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/a/brand/autoShow")
    public String autoShow(HttpServletRequest request, ModelMap modelMap) {
        String cid = ParamUtils.getString(request, "cid", null);
        modelMap.put("cid", cid);
        String bid = ParamUtils.getString(request, "bid", null);
        modelMap.put("bid", bid);
        String prefixURI = ParamUtils.getString(request, "pf", null);
        modelMap.put("prefixURI", prefixURI);
        List<Brand> list = autoFindBrand(cid);
        modelMap.put("brandList", list);
        return "/admin/brand/autoShow";
    }

    /**
     *
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/a/brand/ajax/autoShow", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<String> ajaxAutoShow(HttpServletRequest request, ModelMap modelMap) {
        String cid = ParamUtils.getString(request, "cid", null);
        List<Brand> list = autoFindBrand(cid);
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        AjaxResult rs = new AjaxResult(list, Boolean.TRUE, null);
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    @RequestMapping(value = "/a/brand/list", method = RequestMethod.GET)
    public String showList(HttpServletRequest request, ModelMap modelMap) {
        String flt = com.yeqiangwei.commons.util.ParamHelper.getString(request, "flt", null);
        int total = goodsService.countBrandByFirstLetter(flt);
        Pagination pagination = new Pagination(request, 100);
        List<Brand> brandList = goodsService.findBrandByFirstLetter(flt, pagination);
        pagination.setTotal(total);
        PaginationHelper.setAttribute(request, pagination);
        modelMap.put("brandList", brandList);
        modelMap.put("alphabet", Constants.ALPHABET);
        return "/admin/brand/list";
    }

    @RequestMapping(value = "/a/ajax/brand/modify/list", method = RequestMethod.GET)
    public String ajaxModifyListList(HttpServletRequest request, ModelMap modelMap) {
        String flt = com.yeqiangwei.commons.util.ParamHelper.getString(request, "flt", null);
        int total = goodsService.countBrandByFirstLetter(flt);
        Pagination pagination = new Pagination(request, 100);
        List<Brand> brandList = goodsService.findBrandByFirstLetter(flt, pagination);
        pagination.setTotal(total);
        PaginationHelper.setAttribute(request, pagination);
        modelMap.put("brandList", brandList);
        return "/admin/brand/ajaxModifyList";
    }

    @RequestMapping(value = URI_AJAX_GET, method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<String> ajaxGet(@PathVariable String id) {

        Brand brand = goodsService.getBrandById(id);

        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");


        AjaxResult rs = new AjaxResult(brand, Boolean.TRUE, null);
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }


    @RequestMapping(value = URI_AJAX_LIST, method = RequestMethod.GET)
    public String ajaxList(HttpServletRequest request, ModelMap model) {
        List<Brand> list = goodsService.findAllBrand();
        model.addAttribute("brandList", list);
        return VIEW_AJAX_LIST;
    }

    @RequestMapping(value = URI_SAVE, method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> ajaxSave(@ModelAttribute(COMMAND_NAME) Brand brand
            , BindingResult result, SessionStatus status) {
        AjaxResult rs = null;
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");

        if (ValidatorHelper.isEmpty(brand.getId())
                && goodsService.getBrandByName(brand.getName()) != null) {
            String tmp = brand.getName() + " 品牌已经存在！！！";
            rs = new AjaxResult(brand, Boolean.FALSE, tmp);
        } else {
            goodsService.saveBrand(brand);
            rs = new AjaxResult(brand, Boolean.TRUE, null);

        }

        status.setComplete();

        if (log.isDebugEnabled()) {
            log.debug("#ajaxSave#, id: " + brand.getId()
                    + ", name: " + brand.getName());
        }

        return new ResponseEntity<String>(rs.toJSON(),
                responseHeaders, HttpStatus.CREATED);
    }

    @Resource(name = "goodsService")
    private GoodsService goodsService;
}
